package com.lujianfei.waterpower.ui.power;

import android.content.Context;
import android.text.TextUtils;

import java.io.InputStream;
import java.util.List;

public class PowerModel implements PowerContract.Model {
    @Override
    public List<PowerEntity> getData() {
        List<PowerEntity> powerEntities = PowerEntity.listAll(PowerEntity.class,"set_date desc");
        for (int i = 0; i < powerEntities.size()-1; i++) {
            PowerEntity powerEntity = powerEntities.get(i);
            powerEntity.setNext(powerEntities.get(i+1));
        }
        return powerEntities;
    }

    @Override
    public String getShareContent(Context context, PowerEntity powerEntity) {
        String stringBuilder = getStringFromAssets(context);
        double thisReadout = powerEntity.getReadout();
        double lastReadout = powerEntity.getNext().getReadout();
        double readOutOffset = thisReadout - lastReadout;
        double unitPrice = powerEntity.getNext().getUnit_price();
        double cost = readOutOffset * unitPrice;
        stringBuilder = stringBuilder.replace("[DATE]",powerEntity.getDateStr())
                .replace("[THIS_READOUT]",String.format("%s", thisReadout))
                .replace("[LAST_READOUT]",String.format("%s", lastReadout))
                .replace("[READOUT_OFFSET]",String.format("%s", readOutOffset))
                .replace("[UNIT_PRICE]",String.format("%s", unitPrice))
                .replace("[TOTAL_COST]",String.format("%.1f", cost));
        if (!TextUtils.isEmpty(powerEntity.getRemark())) {
            stringBuilder = stringBuilder.replace("[REMARK]", "备注：" + powerEntity.getRemark());
        } else {
            stringBuilder = stringBuilder.replace("[REMARK]", "");
        }
        return stringBuilder;
    }

    private String getStringFromAssets(Context context) {
        try {
            InputStream inputStream = context.getAssets().open("share_template_power.txt");
            int readSize = 0;
            byte[] b = new byte[1024];
            StringBuilder stringBuilder = new StringBuilder();
            while( -1!=(readSize = inputStream.read(b))){
                stringBuilder.append(new String(b,0,readSize));
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
